package com.es;

import java.net.InetAddress;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

/**
 * @Title: ElasticSearchGet.java
 * @Package com.es
 * @Description: 检索索引库
 *  通过 访问 http://localhost:9200/_plugin/head/
 *  查看数据
 * @author liusongqing
 * @Company www.viewhigh.com
 * @date 2016年9月20日 上午10:47:27
 * @version V1.0
 */
public class ElasticSearchGet {

    public static void main(String[] args) {
        try {
            // 创建客户端
            Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            QueryBuilder qb1 = QueryBuilders.termQuery("title", "hibernate");
            SearchResponse response1 = client.prepareSearch("blog").setTypes("article").setQuery(qb1).execute().actionGet();
            SearchHits hits1 = response1.getHits();
            if (hits1.totalHits() > 0) {
                for (SearchHit hit : hits1) {
                    System.out.println("score:"+hit.getScore()+":\t"+hit.getSource().get("title"));
                }
            } else {
                System.out.println("搜到0条结果");
            }
            QueryBuilder qb2 = QueryBuilders.multiMatchQuery("git", "title", "content");

            SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(qb2).execute().actionGet();
            SearchHits hits = response.getHits();
            if (hits.totalHits() > 0) {
                for (SearchHit hit : hits) {
                    System.out.println("score:"+hit.getScore()+":\t"+hit.getSource());
                }
            } else {
                System.out.println("搜到0条结果");
            }
        } catch (Exception e) {

        }

    }

}
